package cc.yugu.yhdw.webserver.service.hdw;

import cc.yugu.yhdw.common.domain.hdw.Item;
import cc.yugu.yhdw.common.domain.hdw.ItemCategory;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.webserver.persistence.hdw.ItemCategoryMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
/**
 * 商品
 * 
 * @Date:Created in 2018/7/10 16:01
 * @Author:
 * @Modified By: zjn 2018/7/10 16:01
 */ 
@Service
public class ItemService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ItemCategoryMapper itemCategoryMapper;

    public Item find(int id) {
        return itemMapper.find(id);
    }
    /**
    * 分页查询
    * 
    * @Param: [search]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/10  16:01
    */ 
    public Page findPage(Item search) {
        Page page = search.buildPage();
        page.setTotalItems(itemMapper.findPageCount(search));
        search.setBeginIndex(page.getOffset());
        page.setResult(itemMapper.findPageResult(search));
        return page;
    }
    /**
    * 插入商品
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/10  16:09
    */ 
    public ExtResult create(Item entity) {
        ItemCategory category = itemCategoryMapper.find(entity.getCategoryId());
        if(category == null) {
            return ExtResult.failResult("分类不存在");
        }

        entity.setOrderNum(0);
        entity.setCreateTime(new Date());
        itemMapper.insert(entity);
        return ExtResult.successResult();
    }
    /**
    * 更新
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/10  16:09
    */ 
    public ExtResult update(Item entity) {
        ItemCategory category = itemCategoryMapper.find(entity.getCategoryId());
        if(category == null) {
            return ExtResult.failResult("分类不存在");
        }

        itemMapper.update(entity);
        return ExtResult.successResult();
    }
    /**
    * 更新商品编号
    * 
    * @Param: [id, orderNum]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/10  16:09
    */ 
    public ExtResult updateOrderNum(int id, int orderNum) {
        itemMapper.updateOrderNum(id, orderNum);
        return ExtResult.successResult();
    }
    /**
    * 删除
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/10  16:10
    */ 
    public ExtResult delete(int id) {
        itemMapper.delete(id);
        return ExtResult.successResult();
    }
}
